# -*- coding: utf-8 -*-
import re
import json
import math
from iccec.items import iccecSku
from zc_core.model.items import Catalog, ItemDataSupply, Supplier
from zc_core.model.items import ItemData


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    data_json = json.loads(response.text)
    for i in data_json['data']['guideCategorys']:
        for j in i['children']:
            # 一级分类
            cat1_id = j['guideCategoryId']
            cat1_name = j['categoryName']
            cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
            cats.append(cat1)
            for k in j['children']:
                # 二级分类
                cat2_id = k['guideCategoryId']
                cat2_name = k['categoryName']
                cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
                cats.append(cat2)
                for o in k['children']:
                    # 三级分类
                    cat3_id = o['guideCategoryId']
                    cat3_name = o['categoryName']
                    cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                    cats.append(cat3)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析sku列表页数
def parse_total_page(response, pageSize):
    json_data = json.loads(response.text)
    total_page = math.ceil(int(json_data['data']['total']) / pageSize)
    return total_page


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    batch_no = meta.get('batchNo')
    json_data = json.loads(response.text)
    skus = list()
    for i in json_data['data']['result']:
        sku = iccecSku()
        sku['batchNo'] = batch_no
        barCode = i.get('upc')
        if barCode:
            sku['barCode'] = barCode
        sku['catalog3Id'] = str(catalog3Id)
        sku['catalog3Name'] = catalog3Name
        sku['catalog2Id'] = str(catalog2Id)
        sku['catalog2Name'] = catalog2Name
        sku['catalog1Id'] = str(catalog1Id)
        sku['catalog1Name'] = catalog1Name
        sku['supplierId'] = i['shopId']
        sku['supplierName'] = i['shopName']
        sku['skuName'] = i['skuName']
        sku['spuId'] = str(i['spuId'])
        sku['skuImg'] = i['ossSkuMainPic']
        sku['minBuy'] = i['minSaleCount']
        sku['originPrice'] = i['marketPrice']
        sku['salePrice'] = i['salePrice']
        sku['skuId'] = str(i['skuId'])
        skus.append(sku)
    return skus


# 解析sku列表
def parse_sku_supplier(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    supplier_id = meta.get('supplierId')
    json_data = json.loads(response.text)
    skus = list()
    for i in json_data.get('data', {}).get('result', []):
        sku = iccecSku()
        sku['batchNo'] = batch_no
        barCode = i.get('upc')
        if barCode:
            sku['barCode'] = barCode.replace('无', '')
        sku['supplierId'] = supplier_id
        sku['supplierName'] = i.get('shopName')
        sku['skuName'] = i.get('skuName')
        sku['spuId'] = str(i.get('spuId'))
        sku['skuImg'] = i.get('skuMainPic')
        sku['originPrice'] = i.get('marketPrice')
        sku['salePrice'] = i.get('salePrice')
        # print(i.get('salePrice'))
        if not i.get('salePrice'):
            print()
        sku['skuId'] = str(i.get('skuId'))
        sku['clickCount'] = i.get('clicks')
        skus.append(sku)
    return skus


# 解析三级分类详情页
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    supplierName = meta.get('supplierName')
    supplierId = meta.get('supplierId')
    skuImg = meta.get('skuImg')
    originPrice = meta.get('originPrice')
    salePrice = meta.get('salePrice')
    barCode = meta.get('barCode')
    spuId = meta.get('spuId')
    json_data = json.loads(response.text)
    result = ItemData()
    result['skuId'] = sku_id
    result['batchNo'] = batch_no
    result['supplierName'] = supplierName
    result['supplierId'] = supplierId
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    result['catalog1Name'] = catalog1Name
    result['catalog1Id'] = catalog1Id
    result['catalog2Name'] = catalog2Name
    result['catalog2Id'] = catalog2Id
    result['catalog3Name'] = catalog3Name
    result['catalog3Id'] = catalog3Id
    result['spuId'] = spuId
    result['barCode'] = barCode
    result['skuName'] = json_data.get('data', {}).get('skuTitle', '')
    # result['originPrice'] = float(json_data['data']['marketPrice'])
    # result['salePrice'] = float(json_data['data']['salePrice'])
    result['soldCount'] = int(json_data.get('data', {}).get('soldNumber', 0))
    result['originPrice'] = originPrice
    result['salePrice'] = salePrice
    result['minBuy'] = json_data.get('data', {}).get('soldNumber', '')
    result['unit'] = json_data.get('data', {}).get('spuUnitName', '')
    result['skuImg'] = skuImg
    return result


# 解析供应商详情页
def parse_supplier_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    supplierName = meta.get('supplierName')
    supplierId = meta.get('supplierId')
    skuImg = meta.get('skuImg')
    originPrice = meta.get('originPrice')
    salePrice = meta.get('salePrice')
    barCode = meta.get('barCode')
    spuId = meta.get('spuId')
    json_data = json.loads(response.text)
    result = ItemData()
    result['skuId'] = sku_id
    result['batchNo'] = batch_no
    result['supplierName'] = supplierName
    result['supplierId'] = supplierId
    result['spuId'] = spuId
    result['barCode'] = barCode
    result['skuName'] = json_data.get('data', {}).get('skuTitle', '')
    result['soldCount'] = int(json_data.get('data', {}).get('soldNumber', 0))
    result['originPrice'] = originPrice
    result['salePrice'] = salePrice
    result['minBuy'] = json_data.get('data', {}).get('soldNumber', '')
    result['unit'] = json_data.get('data', {}).get('spuUnitName', '')
    result['skuImg'] = skuImg
    return result


# 解析商品编码，品牌
def parse_brand(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    item = ItemDataSupply()
    response_json = json.loads(response.text)
    supplierSkuId_list = [i.get('propValue') for i in response_json.get('data', {}).get('props', []) if
                          i.get('propName') == "商品编码"]
    brandName_list = [i.get('propValue') for i in response_json.get('data', {}).get('props', []) if
                      i.get('propName') == "品牌"]
    if supplierSkuId_list.__len__() != 0:
        item['supplierSkuId'] = supplierSkuId_list[0]
        item['supplierSkuCode'] = supplierSkuId_list[0]
    if brandName_list.__len__() != 0:
        item['brandName'] = brandName_list[0]
    # 批次信息
    item['batchNo'] = batch_no
    # 商品ID
    item['skuId'] = sku_id
    return item


def split_price(leftPrice, rightPrice):
    mean = leftPrice + math.floor((rightPrice - leftPrice) / 2)
    if rightPrice - leftPrice == 1:
        return [[leftPrice, leftPrice], [rightPrice, rightPrice]]
    elif leftPrice != rightPrice:
        return [[leftPrice, mean], [mean, rightPrice]]
    else:
        return []


def parse_catalog_data(response):
    meta = response.meta
    json_data = json.loads(response.text).get('data', {})
    catalog1_id = json_data.get('secCode')
    catalog1_name = json_data.get('secName')
    catalog2_id = json_data.get('thiCode')
    catalog2_name = json_data.get('thiName')
    catalog3_id = json_data.get('fouCode')
    catalog3_name = json_data.get('fouName')
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    result = ItemDataSupply()
    result['catalog1Id'] = catalog1_id
    result['catalog1Name'] = catalog1_name
    result['catalog2Id'] = catalog2_id
    result['catalog2Name'] = catalog2_name
    result['catalog3Id'] = catalog3_id
    result['catalog3Name'] = catalog3_name
    result['skuId'] = sku_id
    result['batchNo'] = batch_no
    return result


def parse_supplier(response):
    json_data = json.loads(response.text)
    data_list = json_data.get('data', {}).get('filterConditions', [])
    if len(data_list) == 6:
        data_list = data_list[2].get('filterValues', [])
        for data in data_list:
            name = data.get('filterValue')
            code = data.get('filterId')
            yield name, code


def parse_supplier_id(response):
    meta = response.meta
    code = meta.get('code')
    batch_no = meta.get('batchNo')
    supplier = Supplier()
    json_data = json.loads(response.text)
    data_list = json_data.get('data', {}).get('result', [])
    for data in data_list:
        supplier['id'] = data.get('shopId')
        supplier['name'] = data.get('shopName')
        supplier['code'] = code
        supplier['batchNo'] = batch_no
    return supplier
